package xin.core.jwt;

import xin.lms.model.AccessLog;
import xin.lms.model.Jwtlog;
import xin.lms.repository.AccessLogRepository;
import xin.lms.repository.JwtlogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.pms.model.User;
import xin.pms.repository.UserRepository;

import java.util.Date;

/**
 * <pre>
 * JwtUserDetailsService implement
 * </pre>
 *
 * @author lixin
 * @since 2017/11/23 10:52
 */
@Service
@Slf4j
@Transactional(readOnly = true)
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AccessLogRepository accessLogRepository;

    @Autowired
    private JwtlogRepository jwtlogRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException(String.format("用户 '%s' 不存在", username));
        } else {
            return JwtUserFactory.create(user);
        }
    }

    /**
     * 登出
     * @param loginLogId 登陆日志ID
     * @param jwt_id jwtId
     */
    @Transactional
    public void exit(String loginLogId,String jwt_id){
        Date logOutTime = new Date(System.currentTimeMillis());
        AccessLog accessLog = accessLogRepository.findOne(loginLogId);
        accessLog.setLogoutTime(logOutTime);
        accessLogRepository.save(accessLog);
        Jwtlog jwtlog = jwtlogRepository.findOne(jwt_id);
        jwtlog.setTokenStatus(Jwtlog.TokenStatus.EXIT.getValue());
        jwtlogRepository.save(jwtlog);
    }
}